<template>  <div>
    <header class="header">
      <el-button @click="$router.push('/student/dashboard')" link class="back-button">
        <img src="@/assets/svgs/left.svg" alt="Back" />
      </el-button>
      <span class="title" style="margin-left: 10px;">AIGC作业</span>
    </header>
    <div><br></div>
    <el-divider content-position="left" style="color: #13227a;">我的作业</el-divider>
    <div><br></div>
    <div class="homework-card-list">
      <el-loading v-if="loading" />
      <template v-else>
        <div v-for="homework in homeworks" :key="homework.id" class="homework-card" @click="handleHomeworkClick(homework)">
          <div>
            <div class="homework-title">{{ homework.title }}</div>
            <div class="homework-teacher">
              教师：{{ homework.teacher || '未知教师' }} 
              <span class="course-info" style="float: right;">课程：{{ homework.course || '未知课程' }}</span>
            </div>
            <div class="homework-dates">
              <div class="publish-time">发布时间：{{ formatDate(homework.publishTime) }}</div>
              <div class="due-time">截止时间：{{ formatDate(homework.dueTime) }}</div>
            </div>
          </div>
          <div class="homework-submission">
            <div class="submission-status">
              <div class="status-text">{{ homework.status || '未知状态' }}</div>
              <div class="status-label">作业状态</div>
            </div>
            <div class="submission-score">
              <div class="score-number">{{ homework.totalScore != null ? homework.totalScore : '-' }}</div>
              <div class="score-label">分数</div>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router';
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getStudentHomeworkService } from '@/api/homework';
import { getStudentCourseList } from '@/api/course';

const route = useRoute();
const router = useRouter();
const homeworks = ref([]);
const loading = ref(false);

// 添加调试信息
onMounted(() => {
  console.log('Route query:', route.query);
  console.log('Route params:', route.params);
  console.log('localStorage courseManageId:', localStorage.getItem('courseManageId'));
  console.log('sessionStorage courseManageId:', sessionStorage.getItem('courseManageId'));
});

// 优化获取作业列表的函数
const fetchHomeworks = async () => {
  loading.value = true;
  try {
    const coursesResponse = await getStudentCourseList();
    
    if (coursesResponse.code === 0 && coursesResponse.data) {
      // 创建课程ID到教师名称和课程名称的映射
      const courseMap = new Map(
        coursesResponse.data.map(course => [course.courseManageId, {
          teacher: course.userName || '未知教师',
          courseName: course.courseName || '未知课程'
        }])
      );

      const homeworkPromises = coursesResponse.data.map(course => 
        getStudentHomeworkService(course.courseManageId)
      );
      
      const homeworkResponses = await Promise.all(homeworkPromises);
      
      const allHomeworks = homeworkResponses
        .filter(response => response.code === 0 && response.data)
        .flatMap(response => response.data)
        .map(homework => {
          const courseInfo = courseMap.get(homework.courseManageId) || { teacher: '未知教师', courseName: '未知课程' };
          return {
            id: homework.homeworkId,
            title: homework.homeworkName,
            teacher: courseInfo.teacher,
            course: courseInfo.courseName,
            publishTime: homework.createTime,
            dueTime: homework.deadline,
            status: homework.state || '未提交',
            totalScore: homework.totalScore,
            questions: homework.question,
            questionIds: homework.questionId,
            scoreSet: homework.scoreSet,
            courseManageId: homework.courseManageId
          };
        });

      homeworks.value = allHomeworks.sort((a, b) => 
        new Date(b.publishTime) - new Date(a.publishTime)
      );
    } else {
      ElMessage.error(coursesResponse.message || '获取课程列表失败');
    }
  } catch (error) {
    console.error('获取作业列表失败:', error);
    ElMessage.error('获取作业列表失败，请稍后重试');
    homeworks.value = [];
  } finally {
    loading.value = false;
  }
};

// 格式化日期的函数
const formatDate = (date) => {
  if (!date) return '未设置';
  const options = { 
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false
  };
  return new Intl.DateTimeFormat('zh-CN', options)
    .format(new Date(date))
    .replace(/\//g, '-')
    .replace(/-/g, '年', 1)
    .replace(/-/g, '月', 1)
    .replace(/\s/, '日 ');
};

// 作业卡片点击处理函数
const handleHomeworkClick = (homework) => {
  const now = new Date();
  const dueTime = new Date(homework.dueTime);
  
  // 检查状态和总分
  if (homework.status === '已截止' && homework.totalScore == null) {
    ElMessage.warning('等待教师批改');
    return; // 阻止跳转
  }

  if (now > dueTime || homework.status === 'SUBMITTED') {
    router.push({
      path: '/student/homework/see_correcthomework',
      query: {
        homeworkId: homework.id,
        title: homework.title,
        dueTime: homework.dueTime,
      }
    });
  } else {
    router.push({
      path: '/student/homework/submit/submit',
      query: {
        homeworkId: homework.id,
        title: homework.title,
        dueTime: homework.dueTime,
      }
    });
  }
};

// 在组件挂载时获取数据
onMounted(() => {
  fetchHomeworks();
});
</script>

<style scoped>
.header {
  color: white;
  height: 30px;
  padding: 10px;
  display: flex;
  align-items: center;
  background-color: #13227a;
  justify-content: flex-start; /* 修改为左对齐 */
}

.back-button {
  color: white;
  border: none;
  width: 25px;
  height: 25px;
}

.el-divider--horizontal {
  margin: 0; /* 移除默认的 margin */
  color: #13227a;
}

.title {
  margin-left: 10px; /* 添加左边距 */
}

.header-right {
  display: flex; /* 使右侧内容为flex布局 */
}

.assign-button {
  background-color: #13227a;
  border: 1px solid white;
  color: white;
  width: 120px;
  height: 40px;
}

.homework-card-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 强制三列布局 */
  gap: 20px;
  padding: 0 40px;
}

.homework-card {
  background-color: white;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 10px;
  height: 220px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.homework-title {
  font-weight: bold;
  color: black;
  font-size: 20px;
}

.homework-teacher {
  color: gray;
  font-size: 14px;
  margin-top: 20px;
}

.course-info {
  color: gray;
  font-size: 14px;
  margin-top: 4px; /* 添加一些上边距 */
  float: center; /* 右对齐课程信息 */
}

.homework-dates {
  color: gray;
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  margin-top: 10px;
}

.publish-time {
  text-align: left;
}

.due-time {
  text-align: right;
}

.homework-submission {
  color: darkgray;
  display: flex;
  justify-content: space-between; /* 改为两端对齐 */
  align-items: center;
  margin-top: 40px;
  padding: 0 20px; /* 添加左右内边距 */
}

.submission-status {
  text-align: left; /* 左对齐 */
}

.status-text {
  font-size: 20px;
  color: #13227a; /* 使用主题蓝色 */
}

.status-label {
  font-size: 14px;
  color: darkgray;
}

.submission-score {
  text-align: right; /* 右对齐 */
}

.score-number {
  font-size: 24px; /* 增大分数数字的字体大小 */
  font-weight: bold; /* 加粗分数数字 */
  color: #13227a; /* 设置分数数字的颜色 */
}
</style>
